/**
 * ChunkRate.java
 */
package objects;

import java.util.Iterator;
import java.util.Set;

import client.RemoteClient;

/**
 * Contains methods for defining when chunk should be dowloaded
 */
public class ChunkRate implements Comparable<ChunkRate> {

    /** */
    private final Integer chunk;

    /** */
    private final Set<RemoteClient> clients;

    /**
     * Constructor
     * @param chunk
     * @param clients
     */
    public ChunkRate(final Integer chunk, final Set<RemoteClient> clients) {
        super();
        this.chunk = chunk;
        this.clients = clients;
    }

    @Override
    public int compareTo(final ChunkRate other) {
        return other.chunk.equals(this.chunk) ? 0 : this.clients.size() - other.clients.size();
    }

    /**
     * @return available client for new leech
     */
    public RemoteClient getDesiredClient() {
        RemoteClient client;
        if (this.clients.size() == 0) {
            client = null;
        } else {
            final Iterator<RemoteClient> iterator = this.clients.iterator();
            client = iterator.next();
            RemoteClient tmp;
            while (iterator.hasNext()) {
                tmp = iterator.next();
                if (client.getUp() > tmp.getUp()) {
                    client = tmp;
                }
            }
        }

        return client;
    }

    /**
     * @return the chunk
     */
    public Integer getChunk() {
        return chunk;
    }

    /**
     * @return the clients
     */
    public Set<RemoteClient> getClients() {
        return clients;
    }



}
